package main
/*本程序由 itruirui@outlook.com 瑞哥 开发制作*/
import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"regexp"
	"errors"
	"time"
)

func main(){
	body, _ := GetHtml("https://hq.smm.cn/cj")	//获取网页的html代码
  str := GetStr(string(body))
	jiage := []byte(str[0][1])
	JiaGe(jiage)
	fmt.Println(string(jiage))
	
	var filename = "./铜排价格记录.txt"
	var f *os.File
	if checkFileIsExist(filename) { //如果文件存在
		f, _ = os.OpenFile(filename, os.O_APPEND, 0666) //打开文件
	} else {
		f, _ = os.Create(filename) //创建文件
	}
	defer f.Close()
	
	t := time.Now()	//获取当前系统时间
	f.Write([]byte(t.String()))
	f.Write([]byte("\r\n长江 1# 电解铜价格："))
	f.WriteString(string(jiage[:len(jiage)]))
	f.Write([]byte("\r\n"))
}
/*
* 获取某个url的html代码
* 参数：url地址
* 返回值：string类型，error类型
*/
func GetHtml(url string)(value string, err error){
	resp, err := http.Get(url)
	if err != nil{
		return
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK{
		err = errors.New(fmt.Sprintln("错误代码：",resp.StatusCode))
		return value, err
	}
	all, err := ioutil.ReadAll(resp.Body)
	if err != nil{
		return
	}
	return string(all), nil
}

/*
* 解析某个string里面的ed2k
* 参数：要解析的string
* 返回值：ed2k内容[][]string
*/
//<span class="orange text-r ellipsis change_price">(.*)</span>
//<span class="green text-r ellipsis change_price">(.*)</span>
func GetStr(body string)(result [][]string){
	reg := regexp.MustCompile("<span class=\"green text-r ellipsis change_price\">(.*)</span>")	//正则表达式规则
	if reg == nil{
		fmt.Println("正则表达式，编译错误：", reg)
		return
	}else{
		result = reg.FindAllStringSubmatch(body, -1)
		return result
	}
}

func JiaGe(by []byte){
	for i, data := range by{
		if data > 'a' && data < 'z'{
			by[i] = data - 'i' + '0'
		}
	}
}

/**
 * 判断文件是否存在  存在返回 true 不存在返回false
 */
func checkFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}